package steampunk.art;

import java.awt.Graphics2D;
import java.awt.image.*;

import steampunk.io.ImageManager;

public class SpriteGrid {
	private BufferedImage grid;
	private int frameWidth = 1;
	private int frameHeight = 1;
	private int width = 1;
	private int height = 1;
	private int frames = 0;
	
	/**
	 * Creates a new sprite grid from the image. This assumes
	 * that all frames have the same dimensions.
	 * @param image - a BufferedImage
	 * @param rows - how many rows of frames there are (vertical)
	 * @param columns - how many columns of frames there are (horizontal)
	 */
	public SpriteGrid(BufferedImage image, int rows, int columns) {
		this.grid = image;
		this.width = image.getWidth();
		this.height = image.getHeight();
		this.frameWidth = width / columns;
		this.frameHeight = height / rows;
		this.frames = rows * columns;
	}

	/**
	 * Creates a new sprite grid from the image. This assumes that
	 * all frames have the same dimensions.
	 * @param image - the file name of the image
	 * @param rows - how many rows of frames there are (vertical)
	 * @param columns - how many columns of frames there are (horizontal)
	 */
	public SpriteGrid(String name, int rows, int columns) {
		this(ImageManager.getImage(name), rows, columns);
	}
	
	/**
	 * Returns the width of a single frame
	 * @return
	 */
	public int getFrameWidth() {
		return frameWidth;
	}
	
	/**
	 * Returns the height of a single frame
	 * @return
	 */
	public int getFrameHeight() {
		return frameHeight;
	}
	
	/**
	 * Draws this frame onto the graphics object. This just
	 * draws the full background image so that the sprite is at the (0, 0)
	 * coordinates, which is desirable this graphics object draws to
	 * a BufferedImage with the width/height of a single frame.
	 * @param g
	 * @param index
	 */
	public void drawFrame(Graphics2D g, int index) {
		int x = (index * frameWidth) % width;
		int y = ((index * frameWidth) / width) * frameHeight;
		g.drawImage(grid, -x, -y, null);
	}
	
	/**
	 * Draws the given frame onto the buffered image at the
	 * (0, 0) coordinates. It is expected that the given
	 * BufferedImage has the dimensions of a single frame.
	 * @param on
	 * @param index
	 */
	public void drawFrame(BufferedImage on, int index) {
		Graphics2D g = on.createGraphics();
		drawFrame(g, index);
		g.dispose();
	}
	
	/**
	 * Creates and returns a new BufferedImage
	 * containing the frame at the given index.
	 * @param index
	 * @return
	 */
	public BufferedImage getFrame(int index) {
		BufferedImage frame
			= new BufferedImage(frameWidth, frameHeight, grid.getType());
		drawFrame(frame, index);
		return frame;
	}
}
